package com.ask.langchain4j_springboot.controller;

import com.ask.langchain4j_springboot.config.AiConfig;
import dev.langchain4j.service.TokenStream;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.LocalDate;

@RestController
@RequestMapping("/memory")
@Tag(name = "记忆对话")
public class MemoryAIController {
    @Autowired
    private AiConfig.Assistant assistant;
    @Autowired
    private AiConfig.AssistantUnique assistantUnique;


    @GetMapping("/chat")
    @Operation(summary = "基础记忆对话")
    public String memoryChat(@RequestParam(defaultValue = "我叫张三") String message) {
        return assistant.chat(message);
    }

    @GetMapping(value = "/memory_stream_chat", produces = "text/stream;charset=UTF-8")
    public Flux<String> memoryStreamChat(@RequestParam(defaultValue = "我是谁") String message, HttpServletResponse response) {
        TokenStream stream = assistant.stream(message, LocalDate.now().toString());

        return Flux.create(sink -> {
            stream.onPartialResponse(s -> sink.next(s))
                    .onCompleteResponse(c -> sink.complete())
                    .onError(sink::error)
                    .start();

        });
    }


    @GetMapping("/memoryId_chat")
    @Operation(summary = "隔离记忆对话")
    public String memoryChat(@RequestParam(defaultValue = "我是谁") String message, Integer userId) {
        return assistantUnique.chat(userId, message);
    }

    @GetMapping("/memoryId_store_chat")
    @Operation(summary = "隔离记忆对话(持久化)")
    public String memoryStoreChat(@RequestParam(defaultValue = "我是谁") String message, Integer userId) {
        return assistantUnique.chat(userId, message);
    }


}
